/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: UpdateDoneReceiver.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.update;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;

import java.io.File;
import java.net.URI;

import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.MD5Utils;
import io.bhex.baselib.utils.SP;
import io.bhex.baselib.utils.ToastUtils;


public class UpdateDoneReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        DebugLog.d("--------------enter-------------");
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
            long downloadId = SP.get(UpdateAgent.DOWNLOAD_ID, -1L);

            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (downloadId != id) {
                return;
            }

            DownloadManager.Query downloadQuery = new DownloadManager.Query();
            downloadQuery.setFilterById(downloadId);

            Cursor cursor = ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).query(downloadQuery);
            try {

                if (cursor.moveToFirst()) {
                    int statusIdx = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);

                    if (cursor.getInt(statusIdx) != DownloadManager.STATUS_SUCCESSFUL) {
                        ToastUtils.showShort("更新文件下载失败");
                        DebugLog.e("Download Failed:" + cursor.getInt(statusIdx));
                        return;
                    }

                    int fileUriIdx = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);

                    String fileUri = cursor.getString(fileUriIdx);

                    //做MD5校验
                    File apkFile = new File(URI.create(fileUri));

                    String md5 = SP.get(UpdateAgent.DOWNLOAD_MD5, "");
                    if (MD5Utils.getFileMD5(apkFile).equals(md5)) {
                        UpdateAgent.startInstall(context, apkFile);
                    } else {
                        DebugLog.e("md5 not equals to " + MD5Utils.getFileMD5(apkFile));
                        if (!apkFile.delete())
                            apkFile.deleteOnExit();
                    }
                }
            } finally {
                cursor.close();
            }

        } else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())) {
            // 下载通知栏点击
            Intent i = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }

    }
}
